#!/bin/bash
# Network mounting script is checks if network is up and 
# see if things are properly mounted then opens folder
# It will time out if it can not connect properly
# Also has a daemon mode that will allow this script
# to be run directly from the command line which can
# be used to ensurse the mount is up but it
# will not open the folder
# daemon mode set at run time $1
# Version 1.5
#
# Created by Andy Fuhr andy@nugeometry.com
##########################################

# SETUP VARIABLES
# Not in USE for reference only, see config file 
################
# Mount Point
# mount_point="/Volumes/"
# Network address to ping, a gateway or server is best
# network_ping_addr="172.26.98.1"
# Network Ping Timeout seconds
# ping_timeo=60
# Max Mount Tries
# max_mount_tries=5
# daemon_mode=1
###################################

# Boolean 0 = not daemon mode, 1 = daemon mode true
daemon_mode=$1

#Set my path
my_path=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )

#Set log file
log_file="${my_path}/logfile.txt"
echo $log_file

# Check to see who is logging in gather information
user=`/usr/bin/stat -f '%Su' /dev/console`

#Source Config File
source "${my_path}/config.txt"

#Show enviroment
echo "Script run at" > "$log_file"
date >> "$log_file"
echo "my_path = ${my_path}" >> "$log_file"
echo "daemon_mode= ${daemon_mode}" >> "$log_file"

#Setup for User Name
#Parse fo Domain\user
#Handle special keyword BLANK
fst_name=`echo $username | awk 'BEGIN { FS ="\\\" } ; { print $1 }'`
snd_name=`echo $username | awk 'BEGIN { FS ="\\\" } ; { print $2 }'`

echo "fst_name = $fst_name" >> "$log_file"
echo "snd_name = $snd_name" >> "$log_file"

if [ "$user" == "root" ]; then
	mount_part=`mount | grep "on ${mount_point}" | awk '{print $2 " " $3}'`
	mount_user=`mount | grep "on ${mount_point}" | sed "s/\([/;:a-zA-Z@\.(, ]*by\) \([a-zA-Z0-9]*\))$/\2/"`
	mount_stat="${mount_part}"
	mount_check="on ${mount_point}"
else
	mount_part=`mount | grep "on ${mount_point}" | awk '{print $2 " " $3}'`
	mount_user=`mount | grep "on ${mount_point}" | sed "s/\([/;:a-zA-Z@\.(, ]*by\) \([a-zA-Z0-9]*\))$/\2/"`
	mount_stat="${mount_part} ${mount_user}"
	mount_check="on ${mount_point} ${user}"
fi

echo "mount_stat = ${mount_stat}" >> "$log_file"
echo "mount_check = ${mount_check}" >> "$log_file"

#Check to see if the share is already mounted. If so then open the folder
#unless we are running in daemon mode
if [ "$mount_stat" == "$mount_check" ]; then
	if [ "${daemon_mode}" != "1" ]; then
		echo "Opening ${mount_point}" >> "$log_file"
		open ${mount_point}/
		exit 0
	else
		exit 0
	fi
fi




#Check to see if network is up
#Try to ping until timeout.  This will allow the app to
#be run on login and aids in the delay that the network
#may take to come up.
loop_counter=0
while [ $loop_counter -ne "${ping_timeo}" ]; do
	
	loop_counter=$[$loop_counter +1]

	echo "Checking to see if networking is up" >> "$log_file"
	#Introduce Delay
        sleep_time=`echo "(${loop_counter}*${loop_counter})/(${loop_counter}+.1)" | bc`
        echo "Sleeping for ${sleep_time}" >> "$log_file"
        sleep $sleep_time
	ping -c 1 "${network_ping_addr}" >> "$log_file"
	
	if [ `echo $?` -eq 0 ]; then
		echo "Ping success" >> "$log_file"
		break
	else
		if [ $loop_counter == "${ping_timeo}" ]; then
			echo "Network Error .  Notifiying user" >> "$log_file"
			myscript="${my_path}/network_error.scpt"
			osascript "$myscript" $daemon_mode
			exit 1
		fi
	fi
	
done

loop_counter=0
while [ "$mount_stat" != "$mount_check" ] && [ $loop_counter -le ${max_mount_tries} ]; do
	
	echo "On loop ${loop_counter} of main mount loop" >> "$log_file"
	#Introduce Delay
	sleep_time=`echo "(${loop_counter}*${loop_counter})/(${loop_counter}+.1)" | bc`
	echo "Sleeping for ${sleep_time}" >> "$log_file"
	sleep $sleep_time

	if [ "$user" == "root" ]; then
		mount_part=`mount | grep "on ${mount_point}" | awk '{print $2 " " $3}'`
		mount_user=`mount | grep "on ${mount_point}" | sed "s/\([/;:a-zA-Z@\.(, ]*by\) \([a-zA-Z0-9]*\))$/\2/"`
		mount_stat="${mount_part}"
		mount_check="on ${mount_point}"
	else
		mount_part=`mount | grep "on ${mount_point}" | awk '{print $2 " " $3}'`
		mount_user=`mount | grep "on ${mount_point}" | sed "s/\([/:;a-zA-Z@\.(, ]*by\) \([a-zA-Z0-9]*\))$/\2/"`
		mount_stat="${mount_part} ${mount_user}"
		mount_check="on ${mount_point} ${user}"
	fi
	
	#Check to see if a symbolic link to that folder exists at the mount 
	#point.  This may be useful when trying to let the system have access
	#to the mount point when no user is logged in.  but then when a user logs
	#in it can remove the link and mount in user context
	if [ -h ${mount_point} ] ; then
		rm ${mount_point}
	fi

	# Remove any mounts for the mount point
	# This may need sudoers file to allow this command
	remove_check=`mount | grep "on ${mount_point}-"`
	echo "Remove Check = '${remove_check}'" >> "$log_file"
	remove_loop_count=0
	while [ "$remove_check" != "" ] && [ $remove_loop_count -le 20 ] ; do

		echo "Trying to remove bad mounts" >> "$log_file"
		#Introduce Delay
		sleep_time=`echo "(${remove_loop_count}*${remove_loop_count})/(${remove_loop_count}+.1)" | bc`
		echo "Sleeping for ${sleep_time}" >> "$log_file"
		sleep $sleep_time
		mountp=`echo $remove_check | awk '{print $3}'`
		
		umount -f "$mountp"
		remove_check=`mount | grep "on ${mount_point}-"`
		remove_loop_count=$[$remove_loop_count +1]
		#If we cant remove these bad mounts something is wrong
		if [ $remove_loop_count -eq 20 ]; then
			echo "Cant remove bad mounts.  Something is wrong." >> "$log_file"
			if [ "${Allow_Share_Enabler}" == "1" ]; then
				echo "Allow Share Enabler is ON trying it..." >> "$log_file"
				touch "$magic_file"
				echo "Disabling Share Enabler so we only try once before failing" >> "$log_file"
				Allow_Share_Enabler="0"
				echo "Reseting loop counter to try again.." >> "$log_file"
				remove_loop_count=0
				#wait a little while for the share enabler to take effect
				sleep 5
				continue
			fi
			
			echo "Should I Alert users there is a problem" >> "$log_file"
			echo "${mount_point}" >> "$log_file"
			echo "${daemon_mode}" >> "$log_file"
			if [ "${daemon_mode}" != "1" ] ; then
					echo "Alerting User that the folder is being used already" >> "$log_file"
					myscript="${my_path}/folder_error.scpt"
					osascript "$myscript" $daemon_mode
					open ${mountp}
			fi
			exit 1
		fi
				
	done

	#Check to see if the mount point folder is already at the location.  If so this will cause an
	#Issue with Finder mounts, incorrectly mounting it at some random folder.  Test the mount point and
	#move the folder to a backup location in case this folder was actually intentionally there

	echo "Checking for mount point destination folder existence." >> $log_file
	if [ -d $mount_point ]; then
		echo "Mount point folder found" >> $log_file
		#Double check this is not mounted
		#add a space to the end to make sure that it is a proper mount
		mount | grep "${mount_point} "
		if [ $? == 0 ]; then
		
			echo "IT IS A MOUNT!!" >> $log_file
			echo "Can't move yet, let the script continue try again later" >> $log_file
		else
			echo "Attempting to move the mount_point folder" >> $log_file
			#set name
			jname=${mount_point}_backup_`date +%Y%m%d_%H%M%S`
			mv -v ${mount_point} ${jname} >> $log_file
			if [ $? == 0 ]; then
				echo "move successful.  Alerting user.." >> $log_file
				myscript="${my_path}/mount_moved.scpt"
				osascript "$myscript" $daemon_mode $jname
			else
				
				echo "Move FAILED..." >> $log_file
			fi
		fi
	fi

	if [ "$user" == "root" ]; then
		mount_part=`mount | grep "on ${mount_point}" | awk '{print $2 " " $3}'`
		mount_user=`mount | grep "on ${mount_point}" | sed "s/\([/;:a-zA-Z@\.(, ]*by\) \([a-zA-Z0-9]*\))$/\2/"`
		mount_stat="${mount_part}"
		mount_check="on ${mount_point}"
	else
		mount_part=`mount | grep "on ${mount_point}" | awk '{print $2 " " $3}'`
		mount_user=`mount | grep "on ${mount_point}" | sed "s/\([/;:a-zA-Z@\.(, ]*by\) \([a-zA-Z0-9]*\))$/\2/"`
		mount_stat="${mount_part} ${mount_user}"
		mount_check="on ${mount_point} ${user}"
	fi
	echo "Attempting to mount share" >> "$log_file"
	echo "Mount stat = '$mount_stat'" >> "$log_file"
	if [ "$mount_check" != "$mount_stat" ]; then	
	
		echo "Trying to mount ${mount_point}" >> "$log_file"
	
		#Mount share with Finder
		myscript="${my_path}/mount_server.scpt"
		osascript "$myscript" $daemon_mode
	else
		echo "Opening ${mount_point}" >> "$log_file"
		open ${mount_point}
	fi
	
	#Check to make sure it mounts at mount point and not some -# of it
	#Gather Curent Mount Stat
	echo "Checking to make sure the mount is up correctly" >> "$log_file"
	if [ "$user" == "root" ]; then
		mount_part=`mount | grep "on ${mount_point}" | awk '{print $2 " " $3}'`
		mount_user=`mount | grep "on ${mount_point}" | sed "s/\([/;:a-zA-Z@\.(, ]*by\) \([a-zA-Z0-9]*\))$/\2/"`
		mount_stat="${mount_part}"
		mount_check="on ${mount_point}"
	else
		mount_part=`mount | grep "on ${mount_point}" | awk '{print $2 " " $3}'`
		mount_user=`mount | grep "on ${mount_point}" | sed "s/\([/;:a-zA-Z@\.(, ]*by\) \([a-zA-Z0-9]*\))$/\2/"`
		mount_stat="${mount_part} ${mount_user}"
		mount_check="on ${mount_point} ${user}"
	fi
	echo "Mount stat = '$mount_stat'" >> "$log_file"
	
	if [ "$fst_name" == "BLANK" ]; then
	
		safety_check=`mount | grep "on ${mount_point}-"`
	else

		safety_check=`mount | grep "on ${mount_point}-"`
	fi
	echo "Saftey Check = '${safety_check}'" >> "$log_file"
	if [ "$safety_check" != "" ] ; then
		echo "Safety Check Failed" >> "$log_file"
		mount_stat=""
		loop_counter=$[$loop_counter +1]
		if [ $loop_counter -ge ${max_mount_tries} ]; then
			#Check to see if a folder where it should mount exists
			#This might be the cause.  Alert User what to do.
			echo "Safety check failed.  Something is wrong." >> "$log_file"
			echo "${mount_point}" >> "$log_file"
			echo "${daemon_mode}" >> "$log_file"
			if [ "${Allow_Share_Enabler}" == "1" ]; then
				echo "Allow Share Enabler is ON trying it..." >> "$log_file"
				touch "$magic_file"
				echo "Disabling Share Enabler so we only try once before failing" >> "$log_file"
				Allow_Share_Enabler="0"
				echo "Reseting loop counter to try again.." >> "$log_file"
				loop_counter=0
				#wait a little while for the share enabler to take effect
				sleep 20
				continue
			fi
			echo "Should I Alert users there is a problem" >> "$log_file"
			#if [ -d ${mount_point} ] && [ "${daemon_mode}" != "1" ] ; then
			if [ "${daemon_mode}" != "1" ] ; then
					echo "Alerting User that the folder is being used already" >> "$log_file"
					myscript="${my_path}/folder_error.scpt"
					osascript "$myscript" $daemon_mode
					open ${mount_point}
			fi
			exit 1
		fi
	fi
	
	
	echo "mount_stat = '${mount_stat}' and mount_check = '${mount_check}'" >> "$log_file"
	echo "Do we need to try again?" >> "$log_file"
	
	loop_counter=$[$loop_counter +1]

	#Check to see if we hit our max tries exit 1
	if [ "${loop_counter}" == "${max_mount_tries}" ]; then
		echo "Something is wrong." >> "$log_file"
		
		#Check to see if a folder where it should mount exists
		#This might be the cause.  Alert User what to do.
		echo "Maxed out tires without success. Something is wrong." >> "$log_file"
		echo "${mount_point}" >> "$log_file"
		echo "${daemon_mode}" >> "$log_file"
		echo "Allow_Share_Enabler =${Allow_Share_Enabler}" >> "$log_file"
		if [ "${Allow_Share_Enabler}" == "1" ]; then
			echo "Allow Share Enabler is ON trying it..." >> "$log_file"
			touch "$magic_file"
			echo "Disabling Share Enabler so we only try once before failing" >> "$log_file"
			Allow_Share_Enabler="0"
			echo "Reseting loop counter to try again.." >> "$log_file"
			loop_counter=0
			#wait a little while for the share enabler to take effect
			sleep 5
			continue
		fi
		echo "Should I Alert users there is a problem" >> "$log_file"
		#if [ -d ${mount_point} ] && [ "${daemon_mode}" != "1" ] ; then
		if [ "${daemon_mode}" != "1" ] ; then
				echo "Alerting User that the folder is being used already" >> "$log_file"
				myscript="${my_path}/folder_error.scpt"
				osascript "$myscript" $daemon_mode
				open ${mount_point}
		fi
		echo "Exiting..." >> "$log_file"
		exit 1
	fi
	
done
